<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter="handleQuery" />
               <!-- <el-select 
          v-model="queryParams.taskId" 
          placeholder="请选择任务" 
          clearable 
          filterable
          @change="handleQuery"
          style="width: 240px;"
        >
          <el-option 
            v-for="item in taskOptions" 
            :key="item.taskId" 
            :label="getTaskLabel(item)" 
            :value="item.taskId"
            :title="getTaskLabel(item)"
          />
        </el-select> -->
      </el-form-item>
     <el-form-item label="发布人" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择发布人" clearable style="width: 150px;">
          <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
          <!-- <el-select 
          v-model="queryParams.userId" 
          placeholder="请选择发布人" 
          clearable 
          filterable
          @change="handleQuery"
          style="width: 240px;"
        >
          <el-option 
            v-for="item in userOptions" 
            :key="item.userId" 
            :label="getUserLabel(item)" 
            :value="item.userId"
            :title="getUserLabel(item)"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item label="地块" prop="plotId">
        <el-select v-model="queryParams.plotId" placeholder="请选择地块" clearable style="width: 150px;">
          <el-option v-for="item in plotOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['peach:task:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['peach:task:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['peach:task:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['peach:task:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="任务ID" align="center" prop="taskId" /> -->
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务描述" align="center" prop="description" />
      <el-table-column label="发布人" align="center" prop="nickName" />
      <el-table-column label="地块" align="center" prop="plotName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-color="#67c23a"
            inactive-color="#f56c6c" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- 修改为查看详细按钮 -->
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"
            v-hasPermi="['peach:task:query']">查看详细</el-button>
          <!-- 注释掉修改和删除按钮 -->
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['peach:task:edit']">修改</el-button> -->
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['peach:task:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或查看数据采集任务对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" :disabled="isDetail" />
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :disabled="isDetail" :rows="3" />
        </el-form-item>
        <el-form-item label="发布人" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择发布人" clearable style="width: 100%" :disabled="isDetail">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地块" prop="plotId">
          <el-select v-model="form.plotId" placeholder="请选择地块" clearable style="width: 100%" :disabled="isDetail">
            <el-option v-for="item in plotOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始时间" :disabled="isDetail" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="YYYY-MM-DD" 
            placeholder="请选择结束时间" :disabled="isDetail" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <!-- 查看详细时显示任务状态 -->
        <el-form-item label="任务状态" v-if="isDetail">
          <el-tag :type="form.status === 1 ? 'success' : 'info'">
            {{ form.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </el-form-item>
        <!-- 查看详细时显示任务ID -->
        <!-- <el-form-item label="任务ID" v-if="isDetail && form.taskId">
          <span>{{ form.taskId }}</span>
        </el-form-item> -->
        <!-- 查看详细时显示创建时间 -->
        <!-- <el-form-item label="创建时间" v-if="isDetail && form.createTime">
          <span>{{ parseTime(form.createTime) }}</span>
        </el-form-item> -->
        <!-- 查看详细时显示更新时间 -->
        <!-- <el-form-item label="更新时间" v-if="isDetail && form.updateTime">
          <span>{{ parseTime(form.updateTime) }}</span>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- 查看详细时只显示关闭按钮 -->
          <el-button v-if="isDetail" @click="cancel">关 闭</el-button>
          <!-- 新增/修改时显示确定和取消按钮 -->
          <template v-else>
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </template>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/peach/task";
import { listUser } from "@/api/system/user";
import { listPlot } from "@/api/peach/plot";
import { onMounted } from 'vue';

const { proxy } = getCurrentInstance();

const taskList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isDetail = ref(false); // 标识是否为查看详细模式
const userOptions = ref([]); // 用户下拉选项
const plotOptions = ref([]); // 地块下拉选项
const taskOptions = ref([]); // 下拉选项

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: null,
    description: null,
    userId: null,
    plotId: null,
    startTime: null,
    endTime: null,
    status: null,
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "发布人不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 任务下拉框 
function getTaskLabel(task) {
  if (!task) return '';
  const labels = [];
  if (task.taskName) labels.push(task.taskName);
  // if (task.taskId) labels.push(`ID:${task.taskId}`);
  // if (task.plotName) labels.push(`地块:${task.plotName}`);
  // if (task.nickName) labels.push(`发布人:${task.nickName}`);
  return labels.join(' | ');
}

// 用户下拉框
function getUserLabel(user) {
  if (!user) return '';
  const labels = [];
  if (user.nickName) labels.push(user.nickName);
  if (user.userName) labels.push(`账号:${user.userName}`);
  if (user.userId) labels.push(`ID:${user.userId}`);
  // if (user.deptName) labels.push(`部门:${user.deptName}`);
  return labels.join(' | ');
}

// 查询任务列表 
function getTaskList() {
  listTask().then(response => {
    taskOptions.value = response.rows || [];
    console.log('任务选项:', taskOptions.value);
  });
}

// 查询用户列表 
function getUserList() {
  listUser({ pageNum: 1, pageSize: 100 }).then(response => {
    userOptions.value = response.rows.map(user => ({
      value: user.userId,
      label: user.nickName
      //user.userName + ' (' + user.nickName + ')' + ' | ID:' + user.userId 
    }));
  });
}

// 查询地块列表 
function getPlotList() {
  listPlot({ pageNum: 1, pageSize: 100 }).then(response => {
    plotOptions.value = response.rows.map(plot => ({
      value: plot.id,
      label: plot.name 
      //plot.name + ' | 地块ID:' + plot.id 
    }));
  });
}

// 查询数据采集任务列表 
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    taskId: null,
    taskName: null,
    description: null,
    userId: null,
    plotId: null,
    startTime: null,
    endTime: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  isDetail.value = false; // 重置详细模式标识
  proxy.resetForm("taskRef");
}

// 搜索按钮操作 
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作 
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作 
function handleAdd() {
  reset();
  isDetail.value = false;
  // 加载用户和地块数据
  getUserList();
  getPlotList();
  open.value = true;
  title.value = "添加数据采集任务";
}

// 查看详细按钮操作 
function handleDetail(row) {
  reset();
  isDetail.value = true; // 设置为查看详细模式
  // 加载用户和地块数据
  getUserList();
  getPlotList();
  const _taskId = row.taskId || ids.value;
  getTask(_taskId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看任务详细信息";
  });
}

// 修改按钮操作 
function handleUpdate(row) {
  reset();
  isDetail.value = false;
  // 加载用户和地块数据
  getUserList();
  getPlotList();
  const _taskId = row.taskId || ids.value
  getTask(_taskId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改数据采集任务";
  });
}

// 提交按钮 
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.taskId != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作 
function handleDelete(row) {
  const _taskIds = row.taskId || ids.value;
  proxy.$modal.confirm('是否确认删除数据采集任务编号为"' + _taskIds + '"的数据项？').then(function () {
    return delTask(_taskIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

// 状态切换操作 
function handleStatusChange(row) {
  // 获取切换后的状态值
  const newStatus = row.status;
  const statusText = newStatus === 1 ? '启用' : '停用';

  // 显示确认对话框
  proxy.$modal.confirm(`是否确认${statusText}任务"${row.taskName}"？`).then(function () {
    // 创建更新数据，只修改状态
    const updateData = {
      taskId: row.taskId,
      status: newStatus
    };
    return updateTask(updateData);
  }).then(() => {
    proxy.$modal.msgSuccess(`${statusText}成功`);
  }).catch(() => {
    // 如果用户取消，则恢复原始状态
    row.status = newStatus === 1 ? 0 : 1;
  });
}

// 导出按钮操作 
function handleExport() {
  proxy.download('peach/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getTaskList();
  getUserList();
  getPlotList();
  getList();
});
</script>
